import random

# Create your views here.
from django.http import HttpResponse
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from celery_tasks.sms.tasks import send_sms_code
from meiduo_mall.utils.captcha.captcha import captcha



class SMSCodeView(APIView):
    """发送短信验证码"""
    def get(self, request, mobile):
        """
        发送短信验证码
        url(r"^sms_codes/(?P<mobile>1[3-9]\d{9})/$", views.SMSCodeView.as_view()),
        :param request:
        :param mobile: 路径传参的手机号
        :return:
        """
        # 1.创建redis链接对象
        redis_conn = get_redis_connection("verify_codes")
        flag = False
        try:
            text = request.query_params["text"].lower()
            image_code_id = request.query_params["image_code_id"]
            print(request.query_params)
            # 1.提取redis中真实的图片那验证码
            real_imgcode = redis_conn.get("img_%s" % image_code_id).decode().lower()
            print(real_imgcode)
            if not real_imgcode:
                flag=True
            if real_imgcode != text:
                flag = True
        except:
            pass
        if flag:
            # 返回响应
            return Response({"message": "图片验证码错误"}, status=400)
        # 2.判断60秒内不允许重复发送短信
        send_flag = redis_conn.get("send_flag_%s" % mobile)
        if send_flag:
            return Response({"message":"发送短信过于频繁"}, status=status.HTTP_400_BAD_REQUEST)
        # 生成短信验证码
        sms_code = "%06d" % random.randint(0, 999999)

        # 发送短信: 调用第三方SDK
        # CCP().send_template_sms(mobile,[sms_code, 300//60], 1)

        # 使用selery发送短信
        # send_sms_code.delay(mobile, sms_code,300//60)
        print("短信验证码:%s" % sms_code)

        # 使用redis管道pipeline缓存sms_code
        pl = redis_conn.pipeline()
        pl.setex("sms_code_%s" % mobile, 300, sms_code)
        pl.setex("send_flag_%s" % mobile, 300, 1)
        # 执行
        pl.execute()

        # 返回响应
        return Response({"message":"OK"},status=200)

    @staticmethod
    def checkSMSCode(mobile):
        """
        验证短信验证码
        :param mobile:
        :param sms_code:
        :return:
        """
        # 建立redis链接
        conn = get_redis_connection("verify_codes")
        real_sms = conn.get("sms_code_%s" % mobile).decode()
        return real_sms


class ImageCheckViews(APIView):
    """图片验证码"""
    def get(self,request, imgid):
        """
        生成团验证码
        image_codes/7aa25ae7-b93b-48df-ba20-669e276352ae/
        :return:
        """
        img_name, text, image = captcha.generate_captcha()
        redis_conn = get_redis_connection("verify_codes")
        redis_conn.setex("img_%s" % imgid, 300, text)
        print("图片验证码:%s" % text)

        # 固定返回验证码图片数据，不需要REST framework框架的Response帮助我们决定返回响应数据的格式
        # 所以此处直接使用Django原生的HttpResponse即可
        return HttpResponse(image, content_type="text/html")

    @staticmethod
    def check_imagecode(imgid):
        """
        获取真实的图片验证码
        :param imgid:
        :return:
        """
        # 建立redis链接
        conn = get_redis_connection("verify_codes")
        real_imgcode = conn.get("img_%s" % imgid).decode()
        return real_imgcode.lower()